package com.SpringBoot.user.service;

import cn.hutool.crypto.SecureUtil;
import com.SpringBoot.Util.JwtUtil;
import com.SpringBoot.Util.Pager;
import com.SpringBoot.Util.RedisService;
import com.SpringBoot.Util.Result;
import com.SpringBoot.mail.MailService;
import com.SpringBoot.security.MyUserDetails;
import com.SpringBoot.user.mapper.UserMapper;
import com.SpringBoot.user.pojo.User;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bxk
 * @since 2025-09-13
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MailService mailService;

    public Result register(User user) {
        User existUser = userMapper.selectByUsername(user.getUsername());
        if (existUser == null) {
            String password = SecureUtil.sha1(user.getPassword());
            user.setPassword(password);
            user.setAddress("http://172.16.1.232:9000/img/6dfe9f2225e748bdaebf6803f6504347.jpg");
            userMapper.register(user);
            return Result.success();
        }
        else{
            return Result.error(400,"账号已存在");
        }
    }

    public void selectByUsername(String username) {
        userMapper.selectByUsername(username);
    }

    public User userInfo(Integer userId) {
        return userMapper.userInfo(userId);
    }

    public Result updateUser(User user) {
        User oldUser = userMapper.selectByUserId(user.getUserId());
        if(oldUser.getIsDeleted()== 1)
        {
            return Result.error(404,"该账户已被删除");
        }
        if(oldUser.equals(user)) {
            return Result.success("更改没有差异，已经取消更改");
        }
        else {
            userMapper.updateUser(user);
            return Result.success();
        }
    }

    public Result updatePasswordByOldPwd(Integer userId, String password, String newPassword) {
        User user = userMapper.selectByUserId(userId);
        if(user == null){
            return Result.error(404,"该用户不存在");
        }
        if(user.getIsDeleted()== 1) {
            return Result.error(404,"该账户已被删除");
        }
        password = SecureUtil.sha1(password);
        newPassword = SecureUtil.sha1(newPassword);
        if(!Objects.equals(user.getPassword(), password)){
            return Result.error(400,"旧密码不对");
        }
        if (Objects.equals(password, newPassword)) {
            return Result.error(400,"新旧密码不能相同");
        }
        if(Objects.equals(password, newPassword)){}
        userMapper.updatePassword(userId,password,newPassword);
        return Result.success("修改成功");

    }

    public Result updatePasswordByEmail(Integer userId, String password, String email,String subject) {
        User user = userMapper.selectByUserId(userId);
        if(user == null){
            return Result.error(404,"该用户不存在");
        }
        if(user.getIsDeleted()== 1) {
            return Result.error(400,"该用户已注销");
        }
        if(mailService.verifyCode(email,subject).getCode() == 200){
            password = SecureUtil.sha1(password);
            userMapper.updatePasswordByEmail(userId,password,email);
            return Result.success("修改成功");
        }
        return mailService.verifyCode(email,subject);
    }

    public HashMap<String,Object> login(User user) throws Exception {
        // 1. 创建一个未认证的 token
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        // 2. 交给 AuthenticationManager 认证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        // 3. 校验认证是否成功
        if (Objects.isNull(authentication) || !authentication.isAuthenticated()) {
            throw new Exception("用户名或密码错误");

        }

        // 4. 获取用户信息
        MyUserDetails myUserDetails = (MyUserDetails) authentication.getPrincipal();
        String userId = myUserDetails.getUser().getUserId().toString();

        // 5. 生成 token
        String token = JwtUtil.createJWT(userId);

        // 6. 存入 Redis
        redisService.setCacheObject("user:" + userId, myUserDetails);

        // 7. 返回结果
        HashMap<String,Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userId", userId);
        return map;
    }

    public Result existUser(Integer userId) {
        User user = userMapper.selectByUserId(userId);
        if(user == null){
            return Result.error(404,"该用户不存在");
        }
        if(user.getIsDeleted() != null && user.getIsDeleted() == 1) {
            return Result.error(404,"该用户已被注销");
        }
        return Result.success("用户存在");
    }

    public Result selectAllUserByPage(Integer pageNum, Integer pageSize){
        System.out.println(pageSize+" "+ pageNum);
        //查询总记录数
        Integer recordCount = userMapper.count();
        //构建分页信息对象
        Pager pager = new Pager(pageNum, pageSize, recordCount);
        //根据pager查询需要的数据
        List<User> list = userMapper.selectAllUser(pager.getStart(), pageSize);
        //将分页信息和查询到的数据一起返回到前端
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",list);
        return Result.success(map);
    }

    public Result getCount(){return Result.success(userMapper.count());}


}
